﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Web.Configuration;
using Formsy.Config.Providers;
using Formsy.Config;

namespace Formsy.Providers.Email
{
    public class EmailProviderManager
    {
        private static EmailProvider m_DefaultProvider;
        private static EmailProviderCollection m_Providers;

        private static string SectionGroupName = Settings.SectionName;
        private static string SectionName = "EmailProviderSettings";


        static EmailProviderManager()
        {
            Initialize();
        }

        private static void Initialize()
        {
            Configuration config = WebConfigurationManager.OpenWebConfiguration("~\\Web.config");
            var group = config.GetSectionGroup(SectionGroupName);

            EmailProviderSettings configuration = (EmailProviderSettings)group.Sections[SectionName];

            if (configuration == null)
                throw new ConfigurationErrorsException("Email Provider configuration section is not set correctly.");

            m_Providers = new EmailProviderCollection();

            ProvidersHelper.InstantiateProviders(configuration.Providers, m_Providers, typeof(EmailProvider));

            m_Providers.SetReadOnly();

            m_DefaultProvider = m_Providers[configuration.Default];

            if (m_DefaultProvider == null)
                throw new Exception("Failed to load provider: " + configuration.Default);
        }

        public static EmailProvider Provider
        {
            get
            {
                return m_DefaultProvider;
            }
        }

        public static EmailProviderCollection Providers
        {
            get
            {
                return m_Providers;
            }
        }
    }
}